package com.jn.rxjava.views;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.jn.rxjava.R;
import com.jn.rxjava.adapter.WeatherApiClient;
import com.jn.rxjava.service.ApiService;
import com.jn.rxjava.service.LifeResponse;
import com.jn.rxjava.service.WeatherResponse;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class WeatherActivity extends AppCompatActivity {
    private EditText cityEditText;
    private Button fetchWeatherButton;
    private TextView weatherTextView;
    private ApiService apiService;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weather);

        cityEditText = findViewById(R.id.city_edit_text);
        fetchWeatherButton = findViewById(R.id.fetch_weather_button);
        weatherTextView = findViewById(R.id.weather_text_view);

        apiService = WeatherApiClient.getRetrofitInstance().create(ApiService.class);

        fetchWeatherButton.setOnClickListener(v -> {
            String city = cityEditText.getText().toString().trim();
            if (city.isEmpty()) {
                Toast.makeText(this, "请输入城市名称", Toast.LENGTH_SHORT).show();
            } else {
                fetchWeatherData(city);
            }
        });
    }

    private void fetchWeatherData(String city) {
        try {

            String requestUrl = "https://apis.juhe.cn/simpleWeather/query?key=7b6f6305357afe3b2eaf962f4045e474&city=" + city;
            Log.d("WeatherActivity", "请求的天气URL: " + requestUrl);

            Disposable disposable = apiService.getWeather("7b6f6305357afe3b2eaf962f4045e474", city)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(response -> {
                        if (response.getError_code() == 0) {
                            displayWeatherInfo(response);
                            fetchLifeIndex(city);  // 获取生活指数
                        } else {
                            Log.e("WeatherActivity", "获取天气失败: " + response.getReason());
                            Toast.makeText(this, "获取天气失败: " + response.getReason(), Toast.LENGTH_SHORT).show();
                        }
                    }, throwable -> {
                        Log.e("WeatherActivity", "获取天气失败: " + throwable.getMessage());
                        Toast.makeText(this, "获取天气失败: " + throwable.getMessage(), Toast.LENGTH_SHORT).show();
                    });
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "城市名称编码失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void fetchLifeIndex(String city) {
        try {
           ;
            String lifeRequestUrl = "https://apis.juhe.cn/simpleWeather/life?key=7b6f6305357afe3b2eaf962f4045e474&city=" + city;
            Log.d("WeatherActivity", "请求的生活指数URL: " + lifeRequestUrl);

            Disposable disposable = apiService.getLifeIndex("7b6f6305357afe3b2eaf962f4045e474", city)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(response -> {
                        if (response.getError_code() == 0) {
                            displayLifeIndex(response);
                        } else {
                            Toast.makeText(this, "获取生活指数失败: " + response.getReason(), Toast.LENGTH_SHORT).show();
                        }
                    }, throwable -> {
                        Toast.makeText(this, "获取生活指数失败: " + throwable.getMessage(), Toast.LENGTH_SHORT).show();
                    });
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "城市名称编码失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void displayWeatherInfo(WeatherResponse response) {
        StringBuilder weatherInfo = new StringBuilder();
        weatherInfo.append("城市: ").append(response.getResult().getCity()).append("\n")
                .append("温度: ").append(response.getResult().getRealtime().getTemperature()).append("°C\n")
                .append("湿度: ").append(response.getResult().getRealtime().getHumidity()).append("%\n")
                .append("天气: ").append(response.getResult().getRealtime().getInfo()).append("\n")
                .append("未来天气:\n");

        for (WeatherResponse.Result.Future future : response.getResult().getFuture()) {
            weatherInfo.append(future.getDate()).append(": ")
                    .append(future.getWeather()).append(" ")
                    .append(future.getTemperature()).append("\n");
        }

        weatherTextView.setText(weatherInfo.toString());
    }

    private void displayLifeIndex(LifeResponse response) {
        StringBuilder lifeInfo = new StringBuilder();
        lifeInfo.append("生活指数:\n");

        if (response.getResult() != null && response.getResult().getLife() != null) {
            lifeInfo.append("空调: ").append(response.getResult().getLife().getKongtiao() != null ? response.getResult().getLife().getKongtiao().getDes() : "无数据").append("\n");
            lifeInfo.append("过敏: ").append(response.getResult().getLife().getGuomin() != null ? response.getResult().getLife().getGuomin().getDes() : "无数据").append("\n");
            lifeInfo.append("舒适度: ").append(response.getResult().getLife().getShushidu() != null ? response.getResult().getLife().getShushidu().getDes() : "无数据").append("\n");
            lifeInfo.append("穿衣: ").append(response.getResult().getLife().getChuanyi() != null ? response.getResult().getLife().getChuanyi().getDes() : "无数据").append("\n");
            lifeInfo.append("钓鱼: ").append(response.getResult().getLife().getDiaoyu() != null ? response.getResult().getLife().getDiaoyu().getDes() : "无数据").append("\n");
            lifeInfo.append("感冒: ").append(response.getResult().getLife().getGanmao() != null ? response.getResult().getLife().getGanmao().getDes() : "无数据").append("\n");
            lifeInfo.append("紫外线: ").append(response.getResult().getLife().getZiwei() != null ? response.getResult().getLife().getZiwei().getDes() : "无数据").append("\n");
            lifeInfo.append("洗车: ").append(response.getResult().getLife().getXiche() != null ? response.getResult().getLife().getXiche().getDes() : "无数据").append("\n");
            lifeInfo.append("运动: ").append(response.getResult().getLife().getYundong() != null ? response.getResult().getLife().getYundong().getDes() : "无数据").append("\n");
        } else {
            lifeInfo.append("无生活指数数据\n");
        }

        weatherTextView.append(lifeInfo.toString());
    }
}
